package com.gitee.chenyaohua.oa.config;

import com.alibaba.fastjson.serializer.ValueFilter;
import com.gitee.chenyaohua.oa.anno.FilterField;
import com.gitee.chenyaohua.oa.from.dto.EncryptionType;
import com.gitee.chenyaohua.oa.util.secret.SecretUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class BeanValueFilter implements ValueFilter{
	
	
	private Map<String,EncryptionType> filter;
	
	

	public BeanValueFilter() {
		super();
		this.filter = new HashMap<>();
	}



	public BeanValueFilter(HashMap<String,EncryptionType> filter) {
		super();
		if(!CollectionUtils.isEmpty(filter)) {
			this.filter.putAll(filter);
		}
	}



	@Override
	public Object process(Object object, String name, Object value) {
		try {
			if(value instanceof String ) {
				String packName = object.getClass().getName();
				if(object instanceof Map) {
					return this.filter.containsKey(name)?getSecretStr(this.filter.get(name), (String) value):value;
				}else if(packName.startsWith("com.gitee.chenyaohua.oa.domain")||packName.startsWith("com.gitee.chenyaohua.oa.from")) {
					Class<? extends Object> class1 = object.getClass();
					Field[] fields = class1.getDeclaredFields();
					if(!ObjectUtils.isEmpty(fields)) {
						for (int i = 0; i < fields.length; i++) {
							Field field = fields[i];
							FilterField ignoreField = field.getAnnotation(FilterField.class);
							if(ignoreField!=null && field.getName().equals(name)) {
								EncryptionType type = ignoreField.type();
								return getSecretStr(type, (String) value);
							}
						}
					}
					
				}
				
				return this.filter.containsKey(name)? getSecretStr(this.filter.get(name), (String) value):value;
			}
		}catch (Exception e) {
			log.error("数据脱敏异常：",e);
		}
		
		return value;
	}


	public  String getSecretStr(EncryptionType type,String value) throws Exception {
		String s = null;
		switch (type){
			case DESEDE:
				s=SecretUtils.des3Encode(value);
				break;
			case MD5:
				s=SecretUtils.md5(value);
				break;
			default:
				s=SecretUtils.md5(value);
				log.error("不存在该类型");
		}
		return s;
	}

}
